package com.iwop.moto.controller;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iwop.moto.comm.Comm;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.utils.file.FileUtil;
import com.iwop.moto.utils.stringUtil.DateUtils;
import com.iwop.moto.utils.stringUtil.ObjectId;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传图片
 * <p>
 *     为CKEDITOR定制的图片上传功能，后续可以扩展上传其他格式的文件
 *  上传的文件的基础路径为: ${apache.home}/${project.name}/${project.name}/resources/upload/img/${'yyyyMMdd'}/
 *  每个文件夹下最多500个文件
 * </p>
 *
 */
@Controller
public class FileUploadController {
	/*
	 *  图片命名格式
	 */
	private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss";
	/*
	 * 项目绝对路径
	 */
	private static  final String PROJECT_PATH="D:/";
	/*
	 * 上传图片文件夹
	 */
	private static final String UPLOAD_PATH="img/";

	/*
	 *  上传图片
	 */
	@RequestMapping("/uploadImg")
	public void uplodaImg(@RequestParam("upload")MultipartFile file,//
			HttpServletRequest request, //
			HttpServletResponse response,//
			@RequestParam("CKEditorFuncNum")String CKEditorFuncNum)//
			throws IllegalStateException, IOException{
		
		PrintWriter out =response.getWriter();
		String fileName=file.getOriginalFilename();
		String uploadContentType =file.getContentType();
		String expandedName ="";
		if (uploadContentType.equals("image/pjpeg")  
                || uploadContentType.equals("image/jpeg")) {  
            // IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg  
            expandedName = ".jpg";  
        } else if (uploadContentType.equals("image/png")  
                || uploadContentType.equals("image/x-png")) {  
            // IE6上传的png图片的headimageContentType是"image/x-png"  
            expandedName = ".png";  
        } else if (uploadContentType.equals("image/gif")) {  
            expandedName = ".gif";  
        } else if (uploadContentType.equals("image/bmp")) {  
            expandedName = ".bmp";  
        } else {  
            out.println("<script type=\"text/javascript\">");  
            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum  
                    + ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');");  
            out.println("</script>");  
            return ;  
        }  
		if (file.getSize()> 600 * 1024) {  
            out.println("<script type=\"text/javascript\">");  
            out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum  
                    + ",''," + "'文件大小不得大于600k');");  
            out.println("</script>");  
            return ;  
		}
		DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
		fileName = df.format(new Date())+expandedName;
		file.transferTo(new File(PROJECT_PATH+UPLOAD_PATH +fileName));
        // 返回"图像"选项卡并显示图片  request.getContextPath()为web项目名   
        out.println("<script type=\"text/javascript\">");  
        out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum  
                + ",'" + "upload/img/" + fileName + "','')");  
        out.println("</script>");  
        return ;  
	}

	@RequestMapping(value = "/mulUpload.do")
	@ResponseBody
	public ResultModel mulUpload(@RequestParam MultipartFile []files, HttpServletRequest request, ModelMap model) {
		ResultModel resultModel=new ResultModel();
		if(files==null){
			resultModel.setCode(0);
			resultModel.setMem("没有上传指定名称files的文件");
			return  resultModel;
		}
		StringBuffer sb=new StringBuffer();
		String date= DateUtils.DateToString(new Date(),"yyyyMMDD");
		for (int i=0;i<files.length;i++){
			MultipartFile file=files[i];
			String path = request.getSession().getServletContext().getRealPath("upload");
			String originalFilename = file.getOriginalFilename();
			String ext=originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
			String fileName = new Date().getTime()+ext;
			path=path+"/"+date;
			File targetFile = new File(path, fileName);
			if(!targetFile.exists()){
				targetFile.mkdirs();
			}
			//保存
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				e.printStackTrace();
			}
			sb.append(request.getContextPath()+"/upload/"+date+"/"+fileName+",");
		}
		resultModel.setData(sb.toString());
		return resultModel;
	}

	@RequestMapping(value = "/upload.do")
	@ResponseBody
	public ResultModel upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
		ResultModel resultModel=new ResultModel();
		//System.out.println("----进入upload.do----");
		String uploadContentType =file.getContentType();
		String originalFilename = file.getOriginalFilename();
		String[] split = originalFilename.split("\\.");
		originalFilename=split[split.length-1];
		String expandedName ="";
		boolean flag=true;
		if (uploadContentType.equals("image/pjpeg")
				|| uploadContentType.equals("image/jpeg")) {
			// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
			expandedName = ".jpg";
		} else if (uploadContentType.equals("image/png")
				|| uploadContentType.equals("image/x-png")) {
			// IE6上传的png图片的headimageContentType是"image/x-png"
			expandedName = ".png";
		} else if (uploadContentType.equals("image/gif")) {
			expandedName = ".gif";
		} else if (uploadContentType.equals("image/bmp")) {
			expandedName = ".bmp";
		}else if (originalFilename.contains("doc")){
			expandedName = ".doc";
		}else if (originalFilename.contains("docx")){
			expandedName = ".docx";
		}else if (originalFilename.contains("ppt")){
			expandedName = ".ppt";
		}else if (originalFilename.contains("pptx")){
			expandedName = ".pptx";
		}else if (originalFilename.contains("xls")){
			expandedName = ".xls";
		}else if (originalFilename.contains("xlsx")){
			expandedName = ".xlsx";
		}else if(originalFilename.contains("apk")){
			expandedName = ".apk";
			flag=false;
		}else if(originalFilename.contains("ipa")){
			expandedName = ".ipa";
			flag=false;
		}else {
			resultModel.setCode(0);
			resultModel.setMem("没有上传指定名称file的文件");
			return  resultModel;
		}
	    if(file==null){
		   resultModel.setCode(0);
		   resultModel.setMem("没有上传指定名称file的文件");
		   return  resultModel;
	    }
		String imgUrl=null;
		if(flag){
			imgUrl= FileUtil.uploadImg(file, Comm.ROOT_PATH);
		}else {
			imgUrl=FileUtil.uploadImg(file, Comm.ROOT_PATH,Comm.APP_UPLOAD_PATH);
		}
		//System.out.println(imgUrl);
		resultModel.setData(imgUrl);
	    return resultModel;
	}

}